import { FC, ReactNode, ChangeEvent } from 'react'
import { useAppDispatch } from '../hooks'
import { updateGoodsState } from '../store/reducers/goods'
import styled from 'styled-components'

const Wrapper = styled.div`
  display: flex;
  padding: 5px 10px;
  .form-check-input {
    margin-top: 43px;
  }
  .thumb {
    width: 100px;
    height: 100px;
    margin-right: 5px;
  }

  .right {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .name {
      font-weight: bold;
    }

    .info {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .price {
        color: red;
        font-weight: bold;
      }
    }
  }
`

type GoodsProps = {
  id: number
  goods_name: string
  goods_img: string
  goods_price: number
  goods_count: number
  goods_state: boolean
  children: ReactNode
}

const Goods: FC<GoodsProps> = (props) => {
  const dispatch = useAppDispatch()
  // 监听复选框选中状态改变的事件
  const onCbChange = (e: ChangeEvent<HTMLInputElement>) => {
    dispatch(updateGoodsState({ id: props.id, value: e.target.checked }))
  }

  return (
    <Wrapper>
      <div>
        <div className="form-check">
          <input className="form-check-input" type="checkbox" checked={props.goods_state} id={'cb' + props.id} onChange={onCbChange} />
          <label className="form-check-label" htmlFor={'cb' + props.id}>
            <img className="thumb" src={props.goods_img} alt="" />
          </label>
        </div>
      </div>
      <div className="right">
        <div className="name">{props.goods_name}</div>
        <div className="info">
          <span className="price">￥{props.goods_price.toFixed(2)}</span>
          {props.children}
        </div>
      </div>
    </Wrapper>
  )
}

export default Goods
